import requestUtil from '../../baseRequest.js'
import requestUrls from '../../requestUrl.js'
import {
  $Message
} from '../../components/base/index'
import commonUtils from '../../utils/util.js'

let openid = wx.getStorageSync('openid')
let uploadUrlCommons ='/api/orderTruck/imageUpload/ORDER_CENTER'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    openId: openid,
    truckCenterId: '',
    isUploadGoodsImage: false,
    //是否提交过
    isSubmit: false,
    fromRegion: [],
    toRegion: [],
    goodsType: '',
    endDate: '',
    fromProvinceId: '',
    fromCityId: '',
    fromCountyId: '',
    fromProvinceName: '',
    fromCityName: '',
    fromCountyName: '',
    toProvinceId: '',
    toCityId: '',
    toCountyId: '',
    toProvinceName: '',
    toCityName: '',
    toCountyName: '',
    startChoiceDate:commonUtils.formatDate(new Date(),'yyyy-MM-dd'),
    beginDate:commonUtils.formatDate(new Date(),'yyyy-MM-dd'),
    goodsTypeList:[
      "易碎品","轻货","重货","设备","配件",
      "建材","家具","食品","塑料粒","玻璃",
      "玩具","灯具","普货","电子产品"
    ],
    truckTypeList: [
      "全部","厢式密封", "厢式尾板", "高栏",
      "低栏", "平板", "冷藏车", "开顶箱车",
    ],
    publishSide: '',
    customItem: '全部',
    uploadGoodsPhoto: {
      itemType: 'uploader',
      title: '货物照片',
      name: 'goodsPhotos',
      files: [],
      count: 9,
      uploadUrl: requestUrls.baseUrl + uploadUrlCommons,
      uploadComplete: 'completeGoodsImgsUpload',
      attentionText: '货物照片最多上传9张图片',
      sourceType: 'camera', //'all/camera'
    },
    orderTruckImageList:[],
    shipperName:'',
    shipperPhone:'',
  },
  /**完成图片上传回调*/
  completeGoodsImgsUpload({ detail }) {
    if(detail && detail.length>0){
      let status = detail.status
    if (status || status == 'error') {
        this.setData({
          showSpin: false,
          isUploadGoodsImage: false,
        })
        return;
    }else{
      let orderTruckImageList = [];
        for(let i=0;i<detail.length;i++){
          orderTruckImageList.push({
            imageUrl:detail[i].url
          })
        }
      this.setData({
        isUploadGoodsImage: false,
        orderTruckImageList : orderTruckImageList,
      })
    }
    }
    wx.hideLoading();
    this.saveOrderCenter();
  },
  submitForm: function (event) {
    const {value={}}= event.detail;
    const {goodsPhotos=[]} = value;
    const orderTruckImageList = [];
    if(goodsPhotos.length>0){
      this.setData({
        isUploadGoodsImage:true,
formDataTemp:{
  openId: this.data.openId,
      criteria: {
        truckCenterId: this.data.truckCenterId,
        orderCenter: {
          fromProvinceId: this.data.fromProvinceId,
          fromCityId: this.data.fromCityId,
          fromCountyId: this.data.fromCountyId,
          fromProvinceName: this.data.fromProvinceName,
          fromCityName: this.data.fromCityName,
          fromCountyName: this.data.fromCountyName,
          toProvinceId: this.data.toProvinceId,
          toCityId: this.data.toCityId,
          toCountyId: this.data.toCountyId,
          toProvinceName: this.data.toProvinceName,
          toCityName: this.data.toCityName,
          toCountyName: this.data.toCountyName,
          fromAddressDetail:value.fromAddressDetail,
          toAddressDetail:value.toAddressDetail,
          loadingBeginTime:this.data.beginDate,
          loadingEndTime:this.data.endDate,
          shipperName:value.shipperName,
          shipperPhone:value.shipperPhone,
          goodsName:value.goodsName,
          goodsTypeName:this.data.goodsType,
          goodsWeight:value.goodsWeight,
          goodsVolume:value.goodsVolume,
          transportFee:value.transportFee,
          receiveName:value.receiveName,
          receivePhone:value.receivePhone,
        }
      }
}
      })
    }
  
  },
  getDriverInfo() {
    if (!this.data.openid) {
      this.setData({
        openid: wx.getStorageSync('openid')
      })
    }
    let param = {
      'openid': this.data.openid
    }
    requestUtil.postRequest(requestUrls.transportConfirm.init, param, (res) => {
      let info = res
      console.log(4444)
      console.log(res);
      this.setData({
        shipperName:res.name,
        shipperPhone:res.mobile,
      })
    }, () => { })

  },
saveOrderCenter(){
  this.data.formDataTemp.criteria.orderCenter.orderTruckImageList = this.data.orderTruckImageList;
if (this.checkData(this.data.formDataTemp)) {
      requestUtil.postRequest(requestUrls.orderCenter.saveOrderCenter, {...this.data.formDataTemp}, (res) => {
        if (!res.hasError) {
          wx.showModal({
            title: '温馨提示',
            content: '操作成功',
            showCancel: false,
            success: res => {
              wx.switchTab({
                url:'/pages/homev2/index'
              })
            }
        })
        }
      })
    }



},
  checkData:function(data){
    const {criteria:{orderCenter}} = data;
    if(orderCenter===null || orderCenter===undefined){
      this.showErrorMessage("提交内容不能为空");
      return false;
    }
    if (orderCenter.fromProvinceId === '' || orderCenter.fromCityId === '' || orderCenter.fromCountyId === '') {
      this.showErrorMessage('出发地信息不能为空');
      return false;
    }
    if(orderCenter.fromAddressDetail===''){
      this.showErrorMessage('出发地详细地址不能为空');
      return false;
    }
    if (orderCenter.toProvinceId === '' || orderCenter.toCityId === '' || orderCenter.toCountyId === '') {
      this.showErrorMessage('目的地信息不能为空');
      return false;
    }
    if(orderCenter.toAddressDetail===''){
      this.showErrorMessage('目的地详细地址不能为空');
      return false;
    }
    if(orderCenter.shipperName===''){
      this.showErrorMessage('货主名称不能为空');
      return false;
    }
    if(commonUtils.isEmoji(orderCenter.shipperName)){
      this.showErrorMessage('货主名称不符合要求');
      return false;
    }
    if(orderCenter.shipperPhone==='' || !commonUtils.checkTelphoneNumber(orderCenter.shipperPhone)){
      this.showErrorMessage('货主手机不符合要求');
      return false;
    }
    if(this.data.goodsType===''){
      this.showErrorMessage('货物类型不能为空');
      return false;
    }
    if(orderCenter.loadingBeginTime===''){
      this.showErrorMessage('装货起始时间不能为空');
      return false;
    }
    // if(orderCenter.loadingBeginTime < this.data.startChoiceDate){
    //   this.showErrorMessage('装货起始时间已过期');
    //   return false;
    // }
    if(orderCenter.loadingEndTime===''){
      this.showErrorMessage('装货截止时间不能为空');
      return false;
    }
    if(orderCenter.loadingEndTime < this.data.startChoiceDate || orderCenter.loadingEndTime <orderCenter.loadingBeginTime){
      this.showErrorMessage('装货截止时间已过期或在装货日期之前');
      return false;
    }
    if(Number(orderCenter.goodsWeight)<0 ||!commonUtils.checkDouble(orderCenter.goodsWeight)){
      this.showErrorMessage('货物重量不符合要求');
      return false;
    }
    if(Number(orderCenter.goodsVolume)<0 ||!commonUtils.checkDouble(orderCenter.goodsVolume)){
      this.showErrorMessage('货物体积不符合要求');
      return false;
    }
    if(Number(orderCenter.transportFee)<0 ||!commonUtils.checkDouble(orderCenter.transportFee)){
      this.showErrorMessage('运费不符合要求');
      return false;
    }
    if(orderCenter.receiveName==='' || commonUtils.isEmoji(orderCenter.receiveName)){
      this.showErrorMessage('卸货方名称不符合要求');
      return false;
    }
    if(orderCenter.receivePhone===''||!commonUtils.checkTelphoneNumber(orderCenter.receivePhone)){
      this.showErrorMessage('卸货方手机号码不符合要求');
      return false;
    }
    // if(orderCenter.orderTruckImageList.length){
    //   this.showErrorMessage('货物图片不能为空');
    //   return false;
    // }

    return true;
  },
  //修改出发地信息
  fromRegionChange: function (e) {
    const regionList = [...e.detail.code, "", "", ""];
    const regionNameList = [...e.detail.value, "", "", ""];
    this.setData({
      fromProvinceId: regionList[0],
      fromCityId: regionList[1],
      fromCountyId: regionList[2],
      fromProvinceName: regionNameList[0],
      fromCityName: regionNameList[1],
      fromCountyName: regionNameList[2],
      fromRegion: e.detail.value
    })
  },
  //修改目的地信息
  toRegionChange: function (e) {
    const regionList = [...e.detail.code, "", "", ""];
    const regionNameList = [...e.detail.value, "", "", ""];
    this.setData({
      toProvinceId: regionList[0],
      toCityId: regionList[1],
      toCountyId: regionList[2],
      toProvinceName: regionNameList[0],
      toCityName: regionNameList[1],
      toCountyName: regionNameList[2],
      toRegion: e.detail.value
    })
  },
  //修改车辆类型
  bindGoodsTypeChange: function (event) {
    const typeValue = event.detail.value;
    this.setData({
      goodsType: this.data.goodsTypeList[typeValue]
    })
  },
  //修改起始时间
  bindBeginDateChange: function (event) {
    this.setData({
      beginDate: event.detail.value
    })
  },
  //修改截止时间
  bindEndDateChange: function (event) {
    this.setData({
      endDate: event.detail.value
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const {
      truckCenterId,
      publishSide
    } = options;
    console.log(truckCenterId+":"+publishSide);
    this.setData({
      truckCenterId: truckCenterId || '',
      publishSide: publishSide || '',
    });
    this.getDriverInfo();
  },
/**显示错误信息 */
  showErrorMessage(msg) {
    $Message({
      content: msg,
      type: 'error'
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
 
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      path: '/pages/homev2/index'
    }
  }
})